using Oracle.ManagedDataAccess.Client;
using Lzfy_His_Service.Models;
using System.Data;

namespace Lzfy_His_Service.Repositories
{
    /// <summary>
    /// 用户基本科室权限查询Repository实现
    /// 使用Oracle HIS数据库
    /// </summary>
    public class UserPermissionRepository : IUserPermissionRepository
    {
        private readonly string _hisConnectionString;

        public UserPermissionRepository(IConfiguration configuration)
        {
            _hisConnectionString = configuration.GetConnectionString("HisOracleConnection") ?? throw new ArgumentNullException("HisOracleConnection connection string not found");
        }

        /// <summary>
        /// 根据用户名查询用户基本科室权限
        /// 使用Oracle HIS数据库
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户权限列表</returns>
        public async Task<List<UserPermissionResponse>> GetUserPermissionsByUsernameAsync(string username)
        {
            var permissions = new List<UserPermissionResponse>();

            const string sql = @"
                SELECT t3.role_name,
                       t2.role_of_context_value,
                       t4.name,
                       t1.people_name,
                       t1.user_name
                  FROM uum.uum_user t1
                  JOIN uum.uum_user_role t2
                    ON t1.id = t2.user_id
                  JOIN uum.uum_role t3
                    ON t2.role_id = t3.id
                   AND t3.role_name = '病历浏览'
                   AND t3.role_name NOT LIKE '%关闭%'
                   AND t3.status = '1'
                  JOIN bds.bds_organization t4
                    ON t2.role_of_context_value = t4.code
                   AND t4.property1='LZ001'
                 WHERE t1.user_name = :username
                   AND t1.status = 'A'";

            try
            {
                using var connection = new OracleConnection(_hisConnectionString);
                await connection.OpenAsync();

                using var command = new OracleCommand(sql, connection);
                command.Parameters.Add(new OracleParameter("username", OracleDbType.Varchar2) { Value = username });

                using var reader = await command.ExecuteReaderAsync();
                while (await reader.ReadAsync())
                {
                    permissions.Add(new UserPermissionResponse
                    {
                        RoleName = reader["role_name"]?.ToString() ?? string.Empty,
                        RoleOfContextValue = reader["role_of_context_value"]?.ToString() ?? string.Empty,
                        Name = reader["name"]?.ToString() ?? string.Empty,
                        PeopleName = reader["people_name"]?.ToString() ?? string.Empty,
                        UserName = reader["user_name"]?.ToString() ?? string.Empty
                    });
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"查询用户基本科室权限失败: {ex.Message}", ex);
            }

            return permissions;
        }
    }
}